<template>
  <page-container>
    <app-card>
      <template #header>
        素材分类
      </template>
      <el-form
        ref="form"
        :model="listParams"
        :disabled="listLoading"
        inline
        @submit.prevent="handleQuery"
      >
        <el-form-item label="分类">
          <el-select
            v-model="listParams.pid"
            filterable
            clearable
            placeholder="请选择分类"
            @change="loadList"
          >
            <el-option
              :value="0"
              label="全部"
            />
            <template
              v-for="item in fileCategories"
              :key="item.id"
            >
              <el-option
                :label="item.name"
                :value="item.id"
              >
                <el-icon
                  v-if="item.children && item.children.length > 0"
                  class="el-icon-arrow-down"
                /> {{ item.name }}
              </el-option>
              <template
                v-if="item.children && item.children.length > 0"
              >
                <el-option
                  v-for="item2 in item.children"
                  :key="item2.id"
                  :label="item2.name"
                  :value="item2.id"
                >
                  <el-icon
                    class="el-icon-arrow-right"
                  />{{ item2.name }}
                </el-option>
              </template>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item style="float: right;">
          <el-button
            type="primary"
            @click="addCate(listParams.pid)"
          >
            添加分类
          </el-button>
        </el-form-item>
      </el-form>
    </app-card>
    <app-card>
      <template #header>
        <!-- <el-button
          type="primary"
          @click="emit('confirm', multipleSelection)"
        >
          使用选中图片
        </el-button> -->
        <el-upload
          action="xxx"
          multiple
          :limit="3"
          :http-request="handleUpload"
          :show-file-list="false"
        >
          <el-button
            type="primary"
          >
            上传图片
          </el-button>
        </el-upload>
        <el-button
          type="danger"
          @click="removeSelected"
          :disabled="multipleSelection.length < 1 || isDeleting"
        >
          删除图片
        </el-button>
        <el-select
          placeholder="图片移动至"
          v-model="moveCate"
          @change="moveSelectedToCate"
          :disabled="multipleSelection.length < 1 || isMoving"
        >
          <el-option
            :value="0"
            label="全部"
          />
          <template
            v-for="item in fileCategories"
            :key="item.id"
          >
            <el-option
              :label="item.name"
              :value="item.id"
            >
              <el-icon
                v-if="item.children && item.children.length > 0"
                class="el-icon-arrow-down"
              /> {{ item.name }}
            </el-option>
            <template
              v-if="item.children && item.children.length > 0"
            >
              <el-option
                v-for="item2 in item.children"
                :key="item2.id"
                :label="item2.name"
                :value="item2.id"
              >
                <el-icon
                  class="el-icon-arrow-right"
                />{{ item2.name }}
              </el-option>
            </template>
          </template>
        </el-select>
      </template>
      <el-table
        :data="list"
        v-loading="listLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column label="图片">
          <template #default="{ row }">
            <el-image
              :key="row.att_id"
              style="width: 50px; height: 50px"
              :src="row.att_dir"
              fit="contain"
              :preview-src-list="[row.att_dir]"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="图片名称"
          prop="real_name"
        />
      </el-table>
      <app-pagination
        v-model:page="listParams.page"
        v-model:limit="listParams.limit"
        :list-count="listCount"
        :load-list="loadList"
        :disabled="listLoading"
      />
    </app-card>
    <app-file-category-form
      v-model="formVisible"
      v-model:cate-id="cateId"
      v-model:pid="pid"
      @success="handleFormSuccess"
    />
  </page-container>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { getFiles, getFileCategories, uploadFile, moveFiles, deleteFile } from '@/api/file'
import type { FileItem, FileCategory } from '@/api/types/file'
import { ElMessage } from 'element-plus'

// const emit = defineEmits(['confirm'])
const fileCategories = ref<FileCategory[]>([])
const list = ref<FileItem[]>([]) // 列表数据
const listCount = ref(0)
const listLoading = ref(true)
const listParams = reactive({ // 列表数据查询参数
  page: 1, // 当前页码
  limit: 10, // 每页大小
  pid: 0
})
const multipleSelection = ref<FileItem[]>([])

const isMoving = ref(false)
const isDeleting = ref(false)

const moveCate = ref('')

const formVisible = ref(false)
const cateId = ref<number|null>(null)
const pid = ref(0)

onMounted(() => {
  loadList()
  loadFileCategories()
})

const addCate = (id: number = 0) => {
  formVisible.value = true
  pid.value = id
}

const handleFormSuccess = () => {
  formVisible.value = false
  cateId.value = null
  loadFileCategories()
}

const handleSelectionChange = (val: FileItem[]) => {
  multipleSelection.value = val
}

const loadList = async () => {
  listLoading.value = true
  const data = await getFiles(listParams).finally(() => {
    listLoading.value = false
  })
  list.value = data.list
  listCount.value = data.count
}

const loadFileCategories = async () => {
  const data = await getFileCategories({ name: '' })
  fileCategories.value = data.list
}

const handleQuery = async () => {
  listParams.page = 1 // 查询默认从第1页开始
  loadList()
}

const removeSelected = async () => {
  if (multipleSelection.value.length < 1) {
    ElMessage.warning('请选择图片')
  } else {
    isDeleting.value = true
    await deleteFile(multipleSelection.value.map(item => item.att_id).join(','))

    multipleSelection.value = []
    ElMessage.success('删除成功')
    isDeleting.value = false
    // 重新加载渲染列表
    listParams.page = 1
    loadList()
  }
}

const moveSelectedToCate = async (pid: number) => {
  if (multipleSelection.value.length < 1) {
    ElMessage.warning('请选择图片')
  } else {
    isMoving.value = true
    await moveFiles({ pid, images: multipleSelection.value.map(item => item.att_id).join(',') })
    ElMessage.success('移动成功')
    isMoving.value = false
    // 重新加载渲染列表
    listParams.page = 1
    loadList()
  }
}

const handleUpload = async ({ file }: { file: File }) => {
  await uploadFile({
    pid: listParams.pid,
    file
  })
  loadList()
}

</script>

<style lang="scss" scoped></style>
